/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.blog;

import java.util.Date;

import com.cenluan.blog.comment.BlogComment;
import com.cenluan.common.Const;
import com.cenluan.ext.jfinal.PkController;
import com.cenluan.kit.UUIDKit;
import com.cenluan.kit.XssKit;
import com.cenluan.login.ClearLoginInterceptor;
import com.cenluan.me.call.Call;
import com.cenluan.me.message.Message;
import com.cenluan.user.User;
import com.cenluan.user.log.UserLog;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;

public class BlogController extends PkController {
	/**
	 * 博客列表,show参数各个值含义:<br>
	 * 1.new，最新的，结果按创建时间倒序排列.<br>
	 * 2.hot,最热，收藏最多的博客.<br>
	 * 3.mine,显示我的相册
	 */
	@ClearLoginInterceptor
	public void index() {
		User user = getSessionAttr(Const.SESSION_USER);
		String show = getPara("show");
		String order = "new";
		String createrId = null;
		if ("hot".equals(show)) {
			order = "hot";
		} else if (user != null && "mine".equals(show)) {
			createrId = user.getStr("id");
		}

		Page<Blog> page = BlogsService.paginate(getPn(), getPara("criteria"),
				createrId, order);

		setPage(page);
		keepPara();
	}

	/**
	 * 添加
	 */
	public void add() {

	}

	/**
	 * 保存
	 */
	@Before(BlogValidator.class)
	public void save() {
		User user = getSessionAttr(Const.SESSION_USER);
		Date lastCreateTime = BlogsService.getLastCreateBlogTime(user
				.getStr("id"));
		// 防止频繁创建博客，限定为5分钟
		if (lastCreateTime != null) {
			long diff = System.currentTimeMillis() - lastCreateTime.getTime();
			if (diff < 1000 * 60 * 5) {
				setAttr("msg", "发表笔记过于频繁");
				renderJson();
				return;
			}
		}
		Blog blog = getModel(Blog.class);
		blog.set("state", Blog.STATE_ACTIVE);
		blog.set("createrId", user.getStr("id"));
		blog.set("createTime", new Date());
		blog.set("updateTime", new Date());
		blog.set("id", UUIDKit.generateUUID());
		if (Blog.TYPE_ORIGINAL.equals(blog.getStr("type"))) {
			blog.remove("referer");
		}
		blog.save();
		setAttr("ok", true);
		setAttr("id", blog.getStr("id"));
		renderJson();
		// 用户动态
		if (!blog.getBoolean("privacy")) {
			UserLog.save(user.getStr("id"), UserLog.TYPE_BLOG,
					blog.getStr("id"));
		}
	}

	/**
	 * 展示，如果是草稿状态，只有创建者本人才能查看
	 */
	public void show() {
		User user = getSessionAttr(Const.SESSION_USER);
		Blog blog = Blog.dao.findById(getPara());
		if (!Blog.STATE_ACTIVE.equals(blog.getStr("state"))) {
			renderError(404);
		}
		if (blog.getBoolean("privacy")
				&& !user.getStr("id").equals(blog.getStr("createrId"))) {
			renderError(403);
		}
		blog.addClickCount();
		setAttr("blog", blog);
		setAttr("favorited",
				BlogsService.hasBeenAddedFavorite(user.getStr("id"),
						blog.getStr("id")));
		boolean isBlogCreater = user.getStr("id").equals(
				blog.getStr("createrId"));
		if (user.isAdmin() || isBlogCreater) {
			setAttr("deletable", true);
		} else {
			setAttr("deletable", false);
		}
		if (isBlogCreater) {
			setAttr("editable", true);
		} else {
			setAttr("editable", false);
		}
		Page<BlogComment> page = BlogComment.dao.page(getPn(), getPara());
		for (BlogComment comment : page.getList()) {
			if (user.isAdmin() || isBlogCreater
					|| user.getStr("id").equals(comment.getStr("createrId"))) {
				comment.put("deletable", true);
			} else {
				comment.put("deletable", false);
			}
		}
		setPage(page);
	}

	/**
	 * 编辑
	 */
	public void edit() {
		User user = getSessionAttr(Const.SESSION_USER);
		Blog blog = Blog.dao.findById(getPara());
		if (!user.getStr("id").equals(blog.getStr("createrId"))) {
			renderError(404);
		}
		setAttr("blog", blog);
	}

	/**
	 * 更新
	 */
	@Before(BlogValidator.class)
	public void update() {
		User user = getSessionAttr(Const.SESSION_USER);
		Blog blog = getModel(Blog.class);
		Blog old = Blog.dao.findById(blog.getStr("id"));
		if (old == null) {
			setAttr("msg", "要更新的博客不存在");
			renderJson();
			return;
		}
		if (!user.getStr("id").equals(old.getStr("createrId"))) {
			setAttr("msg", "无权限的操作");
			renderJson();
			return;
		}

		if (!Blog.STATE_ACTIVE.equals(old.getStr("state"))) {
			setAttr("msg", "该博客已经失效，无法进行更新");
			renderJson();
			return;
		}

		if (Blog.TYPE_ORIGINAL.equals(blog.getStr("type"))) {
			blog.remove("referer");
		}
		blog.set("updateTime", new Date())
				.remove("click_count", "createrId", "createTime").update();
		setAttr("ok", true);
		renderJson();
	}

	/**
	 * 删除
	 */
	public void delete() {
		User user = getSessionAttr(Const.SESSION_USER);
		Blog blog = Blog.dao.findById(getPara());
		if (!user.isAdmin()
				&& !user.getStr("id").equals(blog.getStr("createrId"))) {
			setAttr("msg", "抱歉，您无权限删除此博客");
			renderJson();
			return;
		}
		String title = blog.getStr("title");
		blog.set("state", Blog.STATE_DELETED);
		// 通知
		if (!user.getStr("id").equals(blog.getStr("createrId"))) {
			Message.save(user.getStr("id"), blog.getStr("createrId"),
					"将您的笔记\"" + XssKit.escapeStr(title) + "\"删除");
		}
		blog.keep("id", "state").update();
		setAttr("ok", true);
		renderJson();
		// 删除关联的动态
		UserLog.dao.deleteByReferenceId(getPara());
		Call.dao.deleteByReferenceId(getPara());
	}
}
